/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bookstore.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Web application lifecycle listener.
 * @author Administrator
 */
@WebListener()
public class InitUserNumListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String filename = sce.getServletContext().getRealPath("/WEB-INF/count.txt");
        File file = new File(filename);
        int totalcount = 0;
        if (file.exists()) {
            try {
                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                totalcount = Integer.parseInt(br.readLine());
                br.close();
                fr.close();
            } catch (Exception e) {
            }
        }
        // 进入系统总的用户数
        sce.getServletContext().setAttribute("totalcount", totalcount);
        // 本日来访的用户数
        sce.getServletContext().setAttribute("accesscount", 0);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        String filename = sce.getServletContext().getRealPath("/WEB-INF/count.txt");
        File file = new File(filename);
        try {
            FileWriter fr = new FileWriter(file);
            BufferedWriter br = new BufferedWriter(fr);
            br.write(sce.getServletContext().getAttribute("totalcount").toString());
            br.close();
            fr.close();
        } catch (Exception e) {
        }
    }
}
